package com.system.service;



import com.system.controller.ContentController;
import com.system.controller.MainUIController;
import com.system.domin.MemoUser;
import com.system.menu.UI;
import com.system.untils.SensitiveWordsInspect;

import java.util.InputMismatchException;
import java.util.Scanner;


public class MainPageService {
    public  final Scanner sc;
    private final MainUIController muc;
    private final ContentController cc;
    private final SensitiveWordsInspect swi;
    private final UI ui = new UI();

    public MainPageService() {
        this.muc = new MainUIController();
        this.cc = new ContentController();
        this.swi = new SensitiveWordsInspect();
        this.sc = new Scanner(System.in);
    } 
    // 初始化板子
    // rn   cookies  topics
    public void initMainPageForUser(String email)
    {
//        MemoUser memoUser = muc.getMdm().getInit(email);
        MemoUser memoUser = muc.getMdm().getInit(email);
        ui.main_UI2(memoUser.getName());
    }

    // 添加
    public void addContentM(String email) {
        boolean flag = true;
        while (flag) {
            ui.addContentMenu(muc.getMdm().getName(email));
            System.out.println("请选择（1-2）：");
            try {
                int opt = sc.nextInt();
                switch (opt) {
                    case 1:
                        ui.addContentM(muc.getMdm().getName(email));
                        addContentUser(email);
                        continue;
                    case 2:
                        flag = false;
                        break;
                    default:
                        System.out.println("输入错误！");
                }
            }catch(InputMismatchException e) {
                System.out.println("输入错误，请输入数字！");
                sc.next(); // 清除错误输入
            }
        }
    }

    public void addContentUser(String email)
    {
        sc.nextLine();
        System.out.println("请输入回复内容(连续回车继续输入，输入END结束):");
        String text = multiLineInput();
        // 敏感词检测
        if (this.swi.inspectText(text)) {
            System.out.println("您的输入包含敏感词汇!");
            addContentUser(email);
        }else
        {
            if (this.cc.getUfm().addContext(email,this.muc.getMdm().getName(email),text)) {
                // 同步更新主页内容
                this.muc.getMdm().updateForUserHistory(email);
                this.muc.getMdm().updateAllTopic();
            }
            System.out.println("发表成功！");
        }
    }

    private String multiLineInput() {
        StringBuilder inputBuilder = new StringBuilder();
        while (true) {
            String line = sc.nextLine();
            if ("END".equalsIgnoreCase(line.trim())) { // 判断是否结束输入
                break;
            }
            inputBuilder.append(line).append(System.lineSeparator());
        }
        return inputBuilder.toString().trim(); // 去除多余的换行符
    }
}
